package com.deng.controller;

import com.deng.pojo.User;
import com.deng.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

/**
 * @create 2020-12-14 14:05
 */
@Controller
@Slf4j
public class LoginController {
    @Autowired
    UserService userService;

    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password,
                        String checkbox, Model model, HttpSession session) {
        //如果用户名和密码正确
        if (null != userService.login(username, password)) {
            session.setAttribute("LoginUser", username);
            if (checkbox != null && checkbox.equals("on")) {
                session.setAttribute("name", username);
                session.setAttribute("pwd", password);
            } else {
                session.removeAttribute("name");
                session.removeAttribute("pwd");
            }
            //防止表单重复提交，使用重定向
            return "redirect:/main.html";//跳转到dashboard页面
//            return "dashboard";
        }
        //如果用户名或者密码不正确
        else {
            session.removeAttribute("name");
            session.removeAttribute("pwd");
            model.addAttribute("msg", "用户名或者密码错误");//显示错误信息
            return "index";//跳转到首页
        }
    }

    @RequestMapping("/user/register")
    public String register(@RequestParam("username") String username, @RequestParam("password") String password, Model model, RedirectAttributes redirectAttributes) {

        if (null == userService.findUserByName(username)) {//用户名可用
            if (userService.register(username, password) != 0) {//注册成功
                redirectAttributes.addFlashAttribute("info", "注册成功！请登录");
                return "redirect:/index.html";
            } else {//注册失败
                model.addAttribute("msg", "用户名或者密码错误");//显示错误信息
                return "register";
            }
        } else {
            model.addAttribute("msg", "用户名已被占用");
            return "register";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/user/ajaxreg", produces = "application/json;charset=UTF-8")
    public User ajaxreg(@RequestParam("username") String username) {
        log.info("ajaxreg调用");
        User user = userService.findUserByName(username);
        return user;
    }

    @RequestMapping("/user/toregister")
    public String toregister() {
        return "redirect:/register.html";
    }
}
